package cn.kgc.springboot05.service.impl;

import cn.kgc.springboot05.entity.User;
import cn.kgc.springboot05.mapper.UserMapper;
import cn.kgc.springboot05.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author: mosin
 * @version: v1.0  2022/5/20
 */
@Service
public class UserServiceImpl  implements UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Object getById(Integer id) {
        //查询缓存中 是否有数据
        String key = "user_"+id;
        if(redisTemplate.hasKey(key)){
            Object o = redisTemplate.opsForValue().get(key);
            logger.info("查询的结果来自redis");
            return  o;
        }else{
            User user= userMapper.getById(id);
            redisTemplate.opsForValue().set(key, user);
            logger.info("查询数据来自mysql数据库");
            return user;
        }
    }


    public Integer updateUser(User user) {
        //查询缓存中 是否有数据
        String key = "user_"+user.getId();
        if(redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
            logger.info("redis 缓存已清空");
        }

        return   userMapper.update(user);
    }


}
